package com.yx.shop.dao.admin.impl;

import com.yx.shop.dao.admin.AdminProductDao;
import com.yx.shop.entitly.Address;
import com.yx.shop.entitly.Orders;
import com.yx.shop.entitly.Product;
import com.yx.shop.entitly.Type;
import com.yx.shop.utils.JDBCUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Classname AdminProductDaoImpl
 * @Description TODO:
 * @Date 2021/05/10 19:22
 * @Created by yx
 */
public class AdminProductDaoImpl implements AdminProductDao {
    private QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());

    @Override
    public List<Product> getAllProduct() {
        try {
            String sql = "SELECT pid,product.tid AS tid,pname,ptime,pimage,pprice,pstate,pinfo,tname,tinfo FROM product INNER JOIN TYPE ON product.tid = type.tid;";
            List<Map<String, Object>> query = queryRunner.query(sql, new MapListHandler());
            if (query != null) {
                //保存数据
                List<Product> productList = new ArrayList<>();
                for (Map<String, Object> stringObjectMap : query) {
                    Product product = new Product();
                    Type type = new Type();
                    //封装数据
                    BeanUtils.populate(product, stringObjectMap);
                    BeanUtils.populate(type, stringObjectMap);
                    product.setType(type);
                    productList.add(product);
                }
                return productList;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Integer insertProduct(Product product) {
        try {
            String sql = "INSERT  INTO product(tid,pname,ptime,pimage,pprice,pstate,pinfo) VALUES(?,?,?,?,?,?,?);";
            Object[] args = {product.getTid(),product.getPname(),product.getPtime(),product.getPimage(),product.getPprice(),product.getPstate(),product.getPinfo()};
            return queryRunner.update(sql,args);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
